home *** CD-ROM | disk | FTP | other *** search
/ MacWorld 2003 August / MW 8 2003 CD1.iso / Inside Macworld / Product News / gimp-1.2.4.sit / gimp-1.2.4 / plug-ins / common / jpeg.c < prev    next >
Encoding:
C/C++ Source or Header  |  2003-05-14  |  57.9 KB  |  1,938 lines

  1. /* The GIMP -- an image manipulation program
  2.  * Copyright (C) 1995 Spencer Kimball and Peter Mattis
  3.  *
  4.  * This program is free software; you can redistribute it and/or modify
  5.  * it under the terms of the GNU General Public License as published by
  6.  * the Free Software Foundation; either version 2 of the License, or
  7.  * (at your option) any later version.
  8.  *
  9.  * This program is distributed in the hope that it will be useful,
  10.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.  * GNU General Public License for more details.
  13.  *
  14.  * You should have received a copy of the GNU General Public License
  15.  * along with this program; if not, write to the Free Software
  16.  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  17.  */
  18.  
  19. /* JPEG loading and saving file filter for the GIMP
  20.  *  -Peter Mattis
  21.  *
  22.  * This filter is heavily based upon the "example.c" file in libjpeg.
  23.  * In fact most of the loading and saving code was simply cut-and-pasted
  24.  *  from that file. The filter, therefore, also uses libjpeg.
  25.  */
  26.  
  27. /* 11-JAN-99 - Added support for JPEG comments and Progressive saves.
  28.  *  -pete whiting <pwhiting@sprint.net>
  29.  *
  30.  * Comments of size up to 32k can be stored in the header of jpeg
  31.  * files.  (They are not compressed.)  The JPEG specs and libraries
  32.  * support the storing of multiple comments.  The behavior of this
  33.  * code is to merge all comments in a loading image into a single
  34.  * comment (putting \n between each) and attach that string as a
  35.  * parasite - gimp-comment - to the image.  When saving, the image is
  36.  * checked to see if it has the gimp-comment parasite - if so, that is
  37.  * used as the default comment in the save dialog.  Further, the other
  38.  * jpeg parameters (quaility, smoothing, compression and progressive)
  39.  * are attached to the image as a parasite.  This allows the
  40.  * parameters to remain consistent between saves.  I was not able to
  41.  * figure out how to determine the quaility, smoothing or compression
  42.  * values of an image as it is being loaded, but the code is there to
  43.  * support it if anyone knows how.  Progressive mode is a method of
  44.  * saving the image such that as a browser (or other app supporting
  45.  * progressive loads - gimp doesn't) loads the image it first gets a
  46.  * low res version displayed and then the image is progressively
  47.  * enhanced until you get the final version.  It doesn't add any size
  48.  * to the image (actually it often results in smaller file size) - the
  49.  * only draw backs are that progressive jpegs are not supported by some
  50.  * older viewers/browsers, and some might find it annoying.
  51.  */
  52.  
  53. /* 
  54.  * 21-AUG-99 - Added support for JPEG previews, subsampling,
  55.  *             non-baseline JPEGs, restart markers and DCT method choice
  56.  * - Steinar H. Gunderson <sgunderson@bigfoot.com>
  57.  *
  58.  * A small preview appears and changes according to the changes to the
  59.  * compression options. The image itself works as a much bigger preview.
  60.  * For slower machines, the save operation (not the load operation) is
  61.  * done in the background, with a standard GTK+ idle loop, which turned
  62.  * out to be the most portable way. Win32 porters shouldn't have much
  63.  * difficulty porting my changes (at least I hope so...).
  64.  *
  65.  * Subsampling is a pretty obscure feature, but I thought it might be nice
  66.  * to have it in anyway, for people to play with :-) Does anybody have
  67.  * any better suggestions than the ones I've put in the menu? (See wizard.doc
  68.  * from the libjpeg distribution for a tiny bit of information on subsampling.)
  69.  *
  70.  * A baseline JPEG is often larger and/or of worse quality than a non-baseline
  71.  * one (especially at low quality settings), but all decoders are guaranteed
  72.  * to read baseline JPEGs (I think). Not all will read a non-baseline one.
  73.  *
  74.  * Restart markers are useful if you are transmitting the image over an
  75.  * unreliable network. If a file gets corrupted, it will only be corrupted
  76.  * up to the next restart marker. Of course, if there are no restart markers,
  77.  * the rest of the image will be corrupted. Restart markers take up extra
  78.  * space. The libjpeg developers recommend a restart every 1 row for
  79.  * transmitting images over unreliable networks, such as Usenet.
  80.  *
  81.  * The DCT method is said by the libjpeg docs to _only_ influence quality vs.
  82.  * speed, and nothing else. However, I've found that there _are_ size
  83.  * differences. Fast integer, on the other hand, is faster than integer,
  84.  * which in turn is faster than FP. According to the libjpeg docs (and I
  85.  * believe it's true), FP has only a theoretical advantage in quality, and
  86.  * will be slower than the two other methods, unless you're blessed with
  87.  * very a fast FPU. (In addition, images might not be identical on
  88.  * different types of FP hardware.)
  89.  *
  90.  * ...and thus ends my additions to the JPEG plug-in. I hope. *sigh* :-)
  91.  */
  92.  
  93. /* 
  94.  * 21-AUG-99 - Bunch O' Fixes.
  95.  * - Adam D. Moss <adam@gimp.org>
  96.  *
  97.  * We now correctly create an alpha-padded layer for our preview --
  98.  * having a non-background non-alpha layer is a no-no in GIMP.
  99.  *
  100.  * I've also tweaked the GIMP undo API a little and changed the JPEG
  101.  * plugin to use gimp_image_{freeze,thaw}_undo so that it doesn't store
  102.  * up a whole load of superfluous tile data every time the preview is
  103.  * changed.
  104.  */
  105.  
  106. /*
  107.  * 22-DEC-99 - volatiles added
  108.  * - Austin Donnelly <austin@gimp.org>
  109.  *
  110.  * When gcc complains a variable may be clobbered by a longjmp or
  111.  * vfork, it means the following: setjmp() was called by the JPEG
  112.  * library for error recovery purposes, but gcc is keeping some
  113.  * variables in registers without updating the memory locations on the
  114.  * stack consistently.  If JPEG error recovery is every invoked, the
  115.  * values of these variable will be inconsistent.  This is almost
  116.  * always a bug, but not one that's commonly seen unless JPEG recovery
  117.  * code is exercised frequently.  The correct solution is to tell gcc
  118.  * to keep the stack version of the affected variables up to date, by
  119.  * using the "volatile" keyword.   Here endeth the lesson.
  120.  */
  121.  
  122.  
  123. #include "config.h"   /* configure cares about HAVE_PROGRESSIVE_JPEG */
  124.  
  125. #include <glib.h>     /* We want glib.h first because of some
  126.                * pretty obscure Win32 compilation issues.
  127.                */
  128. #include <setjmp.h>
  129. #include <signal.h>
  130. #include <stdio.h>
  131. #include <stdlib.h>
  132. #include <string.h>
  133. #include <sys/types.h>
  134. #include <sys/stat.h>
  135. #ifdef HAVE_UNISTD_H
  136. #include <unistd.h>
  137. #endif
  138. #include <jpeglib.h>
  139. #include <jerror.h>
  140.  
  141. #include <libgimp/gimp.h>
  142. #include <libgimp/gimpui.h>
  143.  
  144. #include "libgimp/stdplugins-intl.h"
  145.  
  146.  
  147. #define SCALE_WIDTH         125
  148.  
  149. /* if you are not compiling this from inside the gimp tree, you have to  */
  150. /* take care yourself if your JPEG library supports progressive mode     */
  151. /* #undef HAVE_PROGRESSIVE_JPEG   if your library doesn't support it     */
  152. /* #define HAVE_PROGRESSIVE_JPEG  if your library knows how to handle it */
  153.  
  154. #define DEFAULT_QUALITY     0.75
  155. #define DEFAULT_SMOOTHING   0.0
  156. #define DEFAULT_OPTIMIZE    1
  157. #define DEFAULT_PROGRESSIVE 0
  158. #define DEFAULT_BASELINE    1
  159. #define DEFAULT_SUBSMP      0
  160. #define DEFAULT_RESTART     0
  161. #define DEFAULT_DCT         0
  162. #define DEFAULT_PREVIEW     1
  163.  
  164. /* sg - these should not be global... */
  165. static gint32 volatile  image_ID_global       = -1;
  166. static gint32           orig_image_ID_global  = -1;
  167. static gint32           drawable_ID_global    = -1;
  168. static gint32           layer_ID_global       = -1;
  169. static GtkWidget       *preview_size          = NULL;
  170. static GimpDrawable    *drawable_global       = NULL;
  171.  
  172. typedef struct
  173. {
  174.   gdouble quality;
  175.   gdouble smoothing;
  176.   gint    optimize;
  177.   gint    progressive;
  178.   gint    baseline;
  179.   gint    subsmp;
  180.   gint    restart;
  181.   gint    dct;
  182.   gint    preview;
  183. } JpegSaveVals;
  184.  
  185. typedef struct
  186. {
  187.   gint  run;
  188. } JpegSaveInterface;
  189.  
  190. typedef struct 
  191. {
  192.   struct jpeg_compress_struct cinfo;
  193.   gint          tile_height;
  194.   FILE         *outfile;
  195.   gboolean      has_alpha;
  196.   gint          rowstride;
  197.   guchar       *temp;
  198.   guchar       *data;
  199.   guchar       *src;
  200.   GimpDrawable *drawable;
  201.   GimpPixelRgn  pixel_rgn;
  202.   gchar        *file_name;
  203.   gboolean      abort_me;
  204. } PreviewPersistent;
  205.  
  206. static gboolean *abort_me = NULL;
  207.  
  208.  
  209. /* Declare local functions.
  210.  */
  211. static void     query                     (void);
  212. static void     run                       (gchar            *name,
  213.                        gint              nparams,
  214.                        GimpParam        *param,
  215.                        gint             *nreturn_vals,
  216.                        GimpParam       **return_vals);
  217. static gint32   load_image                (gchar            *filename, 
  218.                        GimpRunModeType   runmode, 
  219.                        gboolean          preview);
  220. static gboolean save_image                (gchar            *filename,
  221.                        gint32            image_ID,
  222.                        gint32            drawable_ID,
  223.                        gint32            orig_image_ID,
  224.                        gboolean          preview);
  225.  
  226. static gboolean save_dialog                (void);
  227.  
  228. static void     save_close_callback        (GtkWidget       *widget,
  229.                         gpointer         data);
  230. static void     save_ok_callback           (GtkWidget       *widget,
  231.                         gpointer         data);
  232. static void     save_restart_toggle_update (GtkWidget       *toggle,
  233.                         GtkAdjustment   *adjustment);
  234. static void     save_restart_update        (GtkAdjustment   *adjustment,
  235.                         GtkWidget       *toggle);
  236.  
  237. static void     make_preview               (void);
  238. static void     destroy_preview            (void);
  239.  
  240. static void     menu_callback              (GtkWidget       *widget, 
  241.                         gpointer         data);
  242.  
  243.  
  244. GimpPlugInInfo PLUG_IN_INFO =
  245. {
  246.   NULL,  /* init_proc  */
  247.   NULL,  /* quit_proc  */
  248.   query, /* query_proc */
  249.   run,   /* run_proc   */
  250. };
  251.  
  252. static JpegSaveVals jsvals =
  253. {
  254.   DEFAULT_QUALITY,
  255.   DEFAULT_SMOOTHING,
  256.   DEFAULT_OPTIMIZE,
  257.   DEFAULT_PROGRESSIVE,
  258.   DEFAULT_BASELINE,
  259.   DEFAULT_SUBSMP,
  260.   DEFAULT_RESTART,
  261.   DEFAULT_DCT,
  262.   DEFAULT_PREVIEW
  263. };
  264.  
  265. static JpegSaveInterface jsint =
  266. {
  267.   FALSE   /*  run  */
  268. };
  269.  
  270.  
  271. static gchar     *image_comment         = NULL;
  272. static GtkWidget *restart_markers_scale = NULL;
  273. static GtkWidget *restart_markers_label = NULL;
  274.  
  275.  
  276. MAIN ()
  277.  
  278. static void
  279. query (void)
  280. {
  281.   static GimpParamDef load_args[] =
  282.   {
  283.     { GIMP_PDB_INT32,    "run_mode",     "Interactive, non-interactive" },
  284.     { GIMP_PDB_STRING,   "filename",     "The name of the file to load" },
  285.     { GIMP_PDB_STRING,   "raw_filename", "The name of the file to load" }
  286.   };
  287.   static GimpParamDef load_return_vals[] =
  288.   {
  289.     { GIMP_PDB_IMAGE,   "image",         "Output image" }
  290.   };
  291.   static gint nload_args        = sizeof (load_args) / sizeof (load_args[0]);
  292.   static gint nload_return_vals = (sizeof (load_return_vals) /
  293.                    sizeof (load_return_vals[0]));
  294.  
  295.   static GimpParamDef save_args[] =
  296.   {
  297.     { GIMP_PDB_INT32,    "run_mode",     "Interactive, non-interactive" },
  298.     { GIMP_PDB_IMAGE,    "image",        "Input image" },
  299.     { GIMP_PDB_DRAWABLE, "drawable",     "Drawable to save" },
  300.     { GIMP_PDB_STRING,   "filename",     "The name of the file to save the image in" },
  301.     { GIMP_PDB_STRING,   "raw_filename", "The name of the file to save the image in" },
  302.     { GIMP_PDB_FLOAT,    "quality",      "Quality of saved image (0 <= quality <= 1)" },
  303.     { GIMP_PDB_FLOAT,    "smoothing",    "Smoothing factor for saved image (0 <= smoothing <= 1)" },
  304.     { GIMP_PDB_INT32,    "optimize",     "Optimization of entropy encoding parameters (0/1)" },
  305.     { GIMP_PDB_INT32,    "progressive",  "Enable progressive jpeg image loading - ignored if not compiled with HAVE_PROGRESSIVE_JPEG (0/1)" },
  306.     { GIMP_PDB_STRING,   "comment",      "Image comment" },
  307.     { GIMP_PDB_INT32,    "subsmp",       "The subsampling option number" },
  308.     { GIMP_PDB_INT32,    "baseline",     "Force creation of a baseline JPEG (non-baseline JPEGs can't be read by all decoders) (0/1)" },
  309.     { GIMP_PDB_INT32,    "restart",      "Frequency of restart markers (in rows, 0 = no restart markers)" },
  310.     { GIMP_PDB_INT32,    "dct",          "DCT algorithm to use (speed/quality tradeoff)" }
  311.   };
  312.   static gint nsave_args = sizeof (save_args) / sizeof (save_args[0]);
  313.  
  314.   gimp_install_procedure ("file_jpeg_load",
  315.                           "loads files in the JPEG file format",
  316.                           "loads files in the JPEG file format",
  317.                           "Spencer Kimball, Peter Mattis & others",
  318.                           "Spencer Kimball & Peter Mattis",
  319.                           "1995-1999",
  320.               "<Load>/Jpeg",
  321.               NULL,
  322.                           GIMP_PLUGIN,
  323.                           nload_args, nload_return_vals,
  324.                           load_args, load_return_vals);
  325.  
  326.   gimp_install_procedure ("file_jpeg_save",
  327.                           "saves files in the JPEG file format",
  328.                           "saves files in the lossy, widely supported JPEG format",
  329.                           "Spencer Kimball, Peter Mattis & others",
  330.                           "Spencer Kimball & Peter Mattis",
  331.                           "1995-1999",
  332.                           "<Save>/JPEG",
  333.               "RGB*, GRAY*",
  334.                           GIMP_PLUGIN,
  335.                           nsave_args, 0,
  336.                           save_args, NULL);
  337.  
  338.   gimp_register_magic_load_handler ("file_jpeg_load",
  339.                     "jpg,jpeg",
  340.                     "",
  341.                     "6,string,JFIF,6,string,Exif");
  342.   gimp_register_save_handler       ("file_jpeg_save",
  343.                     "jpg,jpeg",
  344.                     "");
  345. }
  346.  
  347. static void
  348. run (gchar      *name,
  349.      gint        nparams,
  350.      GimpParam  *param,
  351.      gint       *nreturn_vals,
  352.      GimpParam **return_vals)
  353. {
  354.   static GimpParam      values[2];
  355.   GimpRunModeType       run_mode;
  356.   GimpPDBStatusType     status = GIMP_PDB_SUCCESS;
  357.   gint32                image_ID;
  358.   gint32                drawable_ID;
  359.   gint32                orig_image_ID;
  360.   gint32                display_ID = -1;
  361. #ifdef GIMP_HAVE_PARASITES
  362.   GimpParasite         *parasite;
  363. #endif /* GIMP_HAVE_PARASITES */
  364.   gboolean              err;
  365.   GimpExportReturnType  export = GIMP_EXPORT_CANCEL;
  366.  
  367.   run_mode = param[0].data.d_int32;
  368.  
  369.   *nreturn_vals = 1;
  370.   *return_vals  = values;
  371.   values[0].type          = GIMP_PDB_STATUS;
  372.   values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR;
  373.  
  374.   if (strcmp (name, "file_jpeg_load") == 0)
  375.     {
  376.       INIT_I18N_UI();
  377.  
  378.       image_ID = load_image (param[1].data.d_string, run_mode, FALSE);
  379.  
  380.       if (image_ID != -1)
  381.     {
  382.       *nreturn_vals = 2;
  383.       values[1].type         = GIMP_PDB_IMAGE;
  384.       values[1].data.d_image = image_ID;
  385.     }
  386.       else
  387.     {
  388.       status = GIMP_PDB_EXECUTION_ERROR;
  389.     }
  390.     }
  391.   else if (strcmp (name, "file_jpeg_save") == 0)
  392.     {
  393.       INIT_I18N_UI();
  394.  
  395.       image_ID = orig_image_ID = param[1].data.d_int32;
  396.       drawable_ID = param[2].data.d_int32;
  397.  
  398.        /*  eventually export the image */ 
  399.       switch (run_mode)
  400.     {
  401.     case GIMP_RUN_INTERACTIVE:
  402.     case GIMP_RUN_WITH_LAST_VALS:
  403.       gimp_ui_init ("jpeg", FALSE);
  404.       export = gimp_export_image (&image_ID, &drawable_ID, "JPEG", 
  405.                       (GIMP_EXPORT_CAN_HANDLE_RGB |
  406.                        GIMP_EXPORT_CAN_HANDLE_GRAY));
  407.       switch (export)
  408.         {
  409.         case GIMP_EXPORT_EXPORT: 
  410.           display_ID = gimp_display_new (image_ID);
  411.           gimp_image_set_filename (image_ID, _("Export Preview"));
  412.           gimp_displays_flush ();
  413.           break;
  414.         case GIMP_EXPORT_IGNORE:
  415.           break;
  416.         case GIMP_EXPORT_CANCEL:
  417.           values[0].data.d_status = GIMP_PDB_CANCEL;
  418.           return;
  419.           break;
  420.         }
  421.       break;
  422.     default:
  423.       break;
  424.     }
  425.       
  426.       g_free (image_comment);
  427.       image_comment = NULL;
  428.     
  429. #ifdef GIMP_HAVE_PARASITES
  430.       parasite = gimp_image_parasite_find (orig_image_ID, "gimp-comment");
  431.       if (parasite) 
  432.     {
  433.       image_comment = g_strdup (parasite->data);
  434.       gimp_parasite_free (parasite);
  435.     }
  436. #endif /* GIMP_HAVE_PARASITES */
  437.  
  438.       jsvals.quality     = DEFAULT_QUALITY;
  439.       jsvals.smoothing   = DEFAULT_SMOOTHING;
  440.       jsvals.optimize    = DEFAULT_OPTIMIZE;
  441.       jsvals.progressive = DEFAULT_PROGRESSIVE;
  442.       jsvals.baseline    = DEFAULT_BASELINE;
  443.       jsvals.subsmp      = DEFAULT_SUBSMP;
  444.       jsvals.restart     = DEFAULT_RESTART;
  445.       jsvals.dct         = DEFAULT_DCT;
  446.       jsvals.preview     = DEFAULT_PREVIEW;
  447.  
  448.       switch (run_mode)
  449.     {
  450.     case GIMP_RUN_INTERACTIVE:
  451.       /*  Possibly retrieve data  */
  452.       gimp_get_data ("file_jpeg_save", &jsvals);
  453.  
  454. #ifdef GIMP_HAVE_PARASITES
  455.       /* load up the previously used values */
  456.       parasite = gimp_image_parasite_find (orig_image_ID,
  457.                            "jpeg-save-options");
  458.       if (parasite)
  459.         {
  460.           jsvals.quality     = ((JpegSaveVals *)parasite->data)->quality;
  461.           jsvals.smoothing   = ((JpegSaveVals *)parasite->data)->smoothing;
  462.           jsvals.optimize    = ((JpegSaveVals *)parasite->data)->optimize;
  463.           jsvals.progressive = ((JpegSaveVals *)parasite->data)->progressive;
  464.           jsvals.baseline    = ((JpegSaveVals *)parasite->data)->baseline;
  465.           jsvals.subsmp      = ((JpegSaveVals *)parasite->data)->subsmp;
  466.           jsvals.restart     = ((JpegSaveVals *)parasite->data)->restart;
  467.           jsvals.dct         = ((JpegSaveVals *)parasite->data)->dct;
  468.           jsvals.preview     = ((JpegSaveVals *)parasite->data)->preview;
  469.           gimp_parasite_free (parasite);
  470.         }
  471. #endif /* GIMP_HAVE_PARASITES */
  472.  
  473.       /* we start an undo_group and immediately freeze undo saving
  474.          so that we can avoid sucking up tile cache with our unneeded
  475.          preview steps. */
  476.             gimp_undo_push_group_start (image_ID);
  477.             gimp_image_undo_freeze (image_ID);
  478.  
  479.       /* prepare for the preview */
  480.       image_ID_global = image_ID;
  481.       orig_image_ID_global = orig_image_ID;
  482.       drawable_ID_global = drawable_ID;
  483.  
  484.       /*  First acquire information with a dialog  */
  485.       err = save_dialog ();
  486.  
  487.       /* thaw undo saving and end the undo_group. */
  488.       gimp_image_undo_thaw (image_ID);
  489.       gimp_undo_push_group_end (image_ID); 
  490.  
  491.           if (!err)
  492.         status = GIMP_PDB_CANCEL;
  493.       break;
  494.  
  495.     case GIMP_RUN_NONINTERACTIVE:
  496.       /*  Make sure all the arguments are there!  */
  497.       /*  pw - added two more progressive and comment */
  498.       /*  sg - added subsampling, preview, baseline, restarts and DCT */
  499.       if (nparams != 14)
  500.         {
  501.           status = GIMP_PDB_CALLING_ERROR;
  502.         }
  503.       else
  504.         {
  505.           /* Once the PDB gets default parameters, remove this hack */
  506.           if (param[5].data.d_float > 0.05)
  507.         {
  508.           jsvals.quality     = param[5].data.d_float;
  509.           jsvals.smoothing   = param[6].data.d_float;
  510.           jsvals.optimize    = param[7].data.d_int32;
  511. #ifdef HAVE_PROGRESSIVE_JPEG
  512.           jsvals.progressive = param[8].data.d_int32;
  513. #endif /* HAVE_PROGRESSIVE_JPEG */
  514.           jsvals.baseline    = param[11].data.d_int32;
  515.           jsvals.subsmp      = param[10].data.d_int32;
  516.           jsvals.restart     = param[12].data.d_int32;
  517.           jsvals.dct         = param[13].data.d_int32;
  518.  
  519.           /* free up the default -- wasted some effort earlier */
  520.           g_free (image_comment);
  521.           image_comment = g_strdup (param[9].data.d_string);
  522.         }
  523.  
  524.           jsvals.preview = FALSE;
  525.  
  526.           if (jsvals.quality < 0.0 || jsvals.quality > 1.0)
  527.         status = GIMP_PDB_CALLING_ERROR;
  528.           else if (jsvals.smoothing < 0.0 || jsvals.smoothing > 1.0)
  529.         status = GIMP_PDB_CALLING_ERROR;
  530.           else if (jsvals.subsmp < 0 || jsvals.subsmp > 2)
  531.         status = GIMP_PDB_CALLING_ERROR;
  532.           else if (jsvals.dct < 0 || jsvals.dct > 2)
  533.         status = GIMP_PDB_CALLING_ERROR;
  534.         }
  535.       break;
  536.  
  537.     case GIMP_RUN_WITH_LAST_VALS:
  538.       /*  Possibly retrieve data  */
  539.       gimp_get_data ("file_jpeg_save", &jsvals);
  540. #ifdef GIMP_HAVE_PARASITES
  541.       parasite = gimp_image_parasite_find (orig_image_ID,
  542.                            "jpeg-save-options");
  543.       if (parasite)
  544.         {
  545.           jsvals.quality     = ((JpegSaveVals *)parasite->data)->quality;
  546.           jsvals.smoothing   = ((JpegSaveVals *)parasite->data)->smoothing;
  547.           jsvals.optimize    = ((JpegSaveVals *)parasite->data)->optimize;
  548.           jsvals.progressive = ((JpegSaveVals *)parasite->data)->progressive;
  549.           jsvals.baseline    = ((JpegSaveVals *)parasite->data)->baseline;
  550.           jsvals.subsmp      = ((JpegSaveVals *)parasite->data)->subsmp;
  551.           jsvals.restart     = ((JpegSaveVals *)parasite->data)->restart;
  552.           jsvals.dct         = ((JpegSaveVals *)parasite->data)->dct;
  553.           jsvals.preview     = FALSE;
  554.           gimp_parasite_free (parasite);
  555.         }
  556. #endif /* GIMP_HAVE_PARASITES */
  557.       break;
  558.  
  559.     default:
  560.       break;
  561.     }
  562.  
  563.       if (status == GIMP_PDB_SUCCESS)
  564.     {
  565.       if (save_image (param[3].data.d_string,
  566.               image_ID,
  567.               drawable_ID,
  568.               orig_image_ID,
  569.               FALSE))
  570.         {
  571.           /*  Store mvals data  */
  572.           gimp_set_data ("file_jpeg_save", &jsvals, sizeof (JpegSaveVals));
  573.         }
  574.       else
  575.         {
  576.           status = GIMP_PDB_EXECUTION_ERROR;
  577.         }
  578.     }
  579.  
  580.       if (export == GIMP_EXPORT_EXPORT)
  581.     {
  582.       /* If the image was exported, delete the new display. */
  583.       /* This also deletes the image.                       */
  584.  
  585.       if (display_ID > -1)
  586.         gimp_display_delete (display_ID);
  587.       else
  588.         gimp_image_delete (image_ID);
  589.     }
  590.  
  591. #ifdef GIMP_HAVE_PARASITES
  592.       /* pw - now we need to change the defaults to be whatever
  593.        * was used to save this image.  Dump the old parasites
  594.        * and add new ones. */
  595.       
  596.       gimp_image_parasite_detach (orig_image_ID, "gimp-comment");
  597.       if (image_comment && strlen (image_comment)) 
  598.     {
  599.       parasite = gimp_parasite_new ("gimp-comment",
  600.                     GIMP_PARASITE_PERSISTENT,
  601.                     strlen (image_comment) + 1,
  602.                     image_comment);
  603.       gimp_image_parasite_attach (orig_image_ID, parasite);
  604.       gimp_parasite_free (parasite);
  605.     }
  606.       gimp_image_parasite_detach (orig_image_ID, "jpeg-save-options");
  607.       
  608.       parasite = gimp_parasite_new ("jpeg-save-options",
  609.                     0, sizeof (jsvals), &jsvals);
  610.       gimp_image_parasite_attach (orig_image_ID, parasite);
  611.       gimp_parasite_free (parasite);
  612. #endif /* Have Parasites */  
  613.     }
  614.   else
  615.     {
  616.       status = GIMP_PDB_CALLING_ERROR;
  617.     }
  618.  
  619.   values[0].data.d_status = status;
  620. }
  621.  
  622. /* Read next byte */
  623. static guint
  624. jpeg_getc (j_decompress_ptr cinfo)
  625. {
  626.   struct jpeg_source_mgr *datasrc = cinfo->src;
  627.  
  628.   if (datasrc->bytes_in_buffer == 0) 
  629.     {
  630.       if (! (*datasrc->fill_input_buffer) (cinfo))
  631.     ERREXIT (cinfo, JERR_CANT_SUSPEND);
  632.     }
  633.   datasrc->bytes_in_buffer--;
  634.  
  635.   return *datasrc->next_input_byte++;
  636. }
  637.  
  638. /* We need our own marker parser, since early versions of libjpeg
  639.  * don't keep a conventient list of the marker's that have been
  640.  * seen. */
  641.  
  642. /*
  643.  * Marker processor for COM markers.
  644.  * This replaces the library's built-in processor, which just skips the marker.
  645.  * Note this code relies on a non-suspending data source.
  646.  */
  647. static GString *local_image_comments = NULL;
  648.  
  649. static boolean
  650. COM_handler (j_decompress_ptr cinfo)
  651. {
  652.   gint  length;
  653.   guint ch;
  654.  
  655.   length = jpeg_getc (cinfo) << 8;
  656.   length += jpeg_getc (cinfo);
  657.   if (length < 2)
  658.     return FALSE;
  659.   length -= 2;            /* discount the length word itself */
  660.  
  661.   if (!local_image_comments)
  662.     local_image_comments = g_string_new (NULL);
  663.   else
  664.     g_string_append_c (local_image_comments, '\n');
  665.  
  666.   while (length-- > 0)
  667.     {
  668.       ch = jpeg_getc (cinfo);
  669.       g_string_append_c (local_image_comments, ch);
  670.     }
  671.  
  672.   return TRUE;
  673. }
  674.  
  675. typedef struct my_error_mgr
  676. {
  677.   struct jpeg_error_mgr pub;            /* "public" fields */
  678.  
  679.   jmp_buf               setjmp_buffer;  /* for return to caller */
  680. } *my_error_ptr;
  681.  
  682. /*
  683.  * Here's the routine that will replace the standard error_exit method:
  684.  */
  685.  
  686. static void
  687. my_error_exit (j_common_ptr cinfo)
  688. {
  689.   /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
  690.   my_error_ptr myerr = (my_error_ptr) cinfo->err;
  691.  
  692.   /* Always display the message. */
  693.   /* We could postpone this until after returning, if we chose. */
  694.   (*cinfo->err->output_message) (cinfo);
  695.  
  696.   /* Return control to the setjmp point */
  697.   longjmp (myerr->setjmp_buffer, 1);
  698. }
  699.  
  700. static gint32
  701. load_image (gchar           *filename, 
  702.         GimpRunModeType  runmode, 
  703.         gboolean         preview)
  704. {
  705.   GimpPixelRgn     pixel_rgn;
  706.   GimpDrawable    *drawable;
  707.   gint32 volatile  image_ID;
  708.   gint32           layer_ID;
  709.   struct jpeg_decompress_struct cinfo;
  710.   struct my_error_mgr           jerr;
  711.   FILE    *infile;
  712.   guchar  *buf;
  713.   guchar  * volatile padded_buf = NULL;
  714.   guchar **rowbuf;
  715.   gchar   *name;
  716.   gint     image_type;
  717.   gint     layer_type;
  718.   gint     tile_height;
  719.   gint     scanlines;
  720.   gint     i, start, end;
  721.  
  722. #ifdef GIMP_HAVE_PARASITES
  723.   GimpParasite * volatile comment_parasite = NULL;
  724. #endif /* GIMP_HAVE_PARASITES */
  725.  
  726.   /* We set up the normal JPEG error routines. */
  727.   cinfo.err = jpeg_std_error (&jerr.pub);
  728.   jerr.pub.error_exit = my_error_exit;
  729.  
  730.   if ((infile = fopen (filename, "rb")) == NULL)
  731.     {
  732.       g_message (_("can't open \"%s\"\n"), filename);
  733.       gimp_quit ();
  734.     }
  735.  
  736.   if (runmode != GIMP_RUN_NONINTERACTIVE)
  737.     {
  738.       name = g_strdup_printf (_("Loading %s:"), filename);
  739.       gimp_progress_init (name);
  740.       g_free (name);
  741.     }
  742.  
  743.   image_ID = -1;
  744.   /* Establish the setjmp return context for my_error_exit to use. */
  745.   if (setjmp (jerr.setjmp_buffer))
  746.     {
  747.       /* If we get here, the JPEG code has signaled an error.
  748.        * We need to clean up the JPEG object, close the input file, and return.
  749.        */
  750.       jpeg_destroy_decompress (&cinfo);
  751.       if (infile)
  752.     fclose (infile);
  753.       if (image_ID != -1 && !preview)
  754.     gimp_image_delete (image_ID);
  755.       if (preview)
  756.     destroy_preview();
  757.       gimp_quit ();
  758.     }
  759.   /* Now we can initialize the JPEG decompression object. */
  760.   jpeg_create_decompress (&cinfo);
  761.  
  762.   /* Step 2: specify data source (eg, a file) */
  763.  
  764.   jpeg_stdio_src (&cinfo, infile);
  765.  
  766.   /* pw - step 2.1 let the lib know we want the comments. */
  767.  
  768.   jpeg_set_marker_processor (&cinfo, JPEG_COM, COM_handler);
  769.  
  770.   /* Step 3: read file parameters with jpeg_read_header() */
  771.  
  772.   (void) jpeg_read_header (&cinfo, TRUE);
  773.   /* We can ignore the return value from jpeg_read_header since
  774.    *   (a) suspension is not possible with the stdio data source, and
  775.    *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
  776.    * See libjpeg.doc for more info.
  777.    */
  778.  
  779. #ifdef GIMP_HAVE_PARASITES
  780.   if (!preview) 
  781.     {
  782.       /* if we had any comments then make a parasite for them */
  783.       if (local_image_comments && local_image_comments->len) 
  784.     {
  785.       gchar *string = local_image_comments->str;
  786.       g_string_free (local_image_comments, FALSE);
  787.       local_image_comments = NULL;
  788.       comment_parasite = gimp_parasite_new ("gimp-comment",
  789.                         GIMP_PARASITE_PERSISTENT,
  790.                         strlen (string) + 1, string);
  791.     } 
  792.       else 
  793.     {
  794.       comment_parasite = NULL;
  795.     }
  796.       
  797.       /* Do not attach the "jpeg-save-options" parasite to the image
  798.        * because this conflics with the global defaults.  See bug #75398:
  799.        * http://bugzilla.gnome.org/show_bug.cgi?id=75398 */
  800.     } 
  801. #endif /* GIMP_HAVE_PARASITES */
  802.   
  803.   
  804.   /* Step 4: set parameters for decompression */
  805.  
  806.   /* In this example, we don't need to change any of the defaults set by
  807.    * jpeg_read_header(), so we do nothing here.
  808.    */
  809.  
  810.   /* Step 5: Start decompressor */
  811.  
  812.   jpeg_start_decompress (&cinfo);
  813.  
  814.   /* We may need to do some setup of our own at this point before reading
  815.    * the data.  After jpeg_start_decompress() we have the correct scaled
  816.    * output image dimensions available, as well as the output colormap
  817.    * if we asked for color quantization.
  818.    * In this example, we need to make an output work buffer of the right size.
  819.    */
  820.   /* temporary buffer */
  821.   tile_height = gimp_tile_height ();
  822.   buf = g_new (guchar, 
  823.            tile_height * cinfo.output_width * cinfo.output_components);
  824.   
  825.   rowbuf = g_new (guchar*, tile_height);
  826.  
  827.   for (i = 0; i < tile_height; i++)
  828.     rowbuf[i] = buf + cinfo.output_width * cinfo.output_components * i;
  829.  
  830.   /* Create a new image of the proper size and associate the filename with it.
  831.  
  832.      Preview layers, not being on the bottom of a layer stack, MUST HAVE
  833.      AN ALPHA CHANNEL!
  834.    */
  835.   switch (cinfo.output_components)
  836.     {
  837.     case 1:
  838.       image_type = GIMP_GRAY;
  839.       layer_type = preview ? GIMP_GRAYA_IMAGE : GIMP_GRAY_IMAGE;
  840.       break;
  841.  
  842.     case 3:
  843.       image_type = GIMP_RGB;
  844.       layer_type = preview ? GIMP_RGBA_IMAGE : GIMP_RGB_IMAGE;
  845.       break;
  846.  
  847.     case 4:
  848.       if (cinfo.out_color_space == JCS_CMYK)
  849.     {
  850.       image_type = GIMP_RGB;
  851.       layer_type = GIMP_RGB_IMAGE;
  852.       break;
  853.     }
  854.       /*fallthrough*/
  855.  
  856.     default:
  857.       g_message ("don't know how to load JPEGs\nwith %d color channels\nusing colorspace %d (%d)",
  858.          cinfo.output_components, cinfo.out_color_space,
  859.          cinfo.jpeg_color_space);
  860.       gimp_quit ();
  861.       break;
  862.     }
  863.  
  864.   if (preview)
  865.     padded_buf = g_new (guchar, tile_height * cinfo.output_width *
  866.             (cinfo.output_components + 1));
  867.   else if (cinfo.out_color_space == JCS_CMYK)
  868.     padded_buf = g_new (guchar, tile_height * cinfo.output_width * 3);
  869.   else
  870.     padded_buf = NULL;
  871.  
  872.   if (preview) 
  873.     {
  874.       image_ID = image_ID_global;
  875.     } 
  876.   else 
  877.     {
  878.       image_ID = gimp_image_new (cinfo.output_width, cinfo.output_height,
  879.                  image_type);
  880.       gimp_image_set_filename (image_ID, filename);
  881.     }
  882.  
  883.   if (preview) 
  884.     {
  885.       layer_ID_global = layer_ID = 
  886.     gimp_layer_new (image_ID, _("JPEG preview"),
  887.             cinfo.output_width,
  888.             cinfo.output_height,
  889.             layer_type, 100, GIMP_NORMAL_MODE);
  890.     }
  891.   else 
  892.     {
  893.       layer_ID = gimp_layer_new (image_ID, _("Background"),
  894.                  cinfo.output_width,
  895.                  cinfo.output_height,
  896.                  layer_type, 100, GIMP_NORMAL_MODE);
  897.     }
  898.  
  899.   drawable_global = drawable = gimp_drawable_get (layer_ID);
  900.   gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0,
  901.                drawable->width, drawable->height, TRUE, FALSE);
  902.  
  903. #ifdef GIMP_HAVE_RESOLUTION_INFO
  904.   /* Step 5.1: if the file had resolution information, set it on the image */
  905.   if (!preview && cinfo.saw_JFIF_marker)
  906.     {
  907.       gdouble xresolution;
  908.       gdouble yresolution;
  909.       gdouble asymmetry;
  910.  
  911.       xresolution = cinfo.X_density;
  912.       yresolution = cinfo.Y_density;
  913.  
  914.       switch (cinfo.density_unit)
  915.     {
  916.     case 0: /* unknown -> set the aspect ratio but use the default
  917.         *  image resolution
  918.         */
  919.       if (cinfo.Y_density != 0)
  920.         asymmetry = xresolution / yresolution;
  921.       else
  922.         asymmetry = 1.0;
  923.  
  924.       gimp_image_get_resolution (image_ID, &xresolution, &yresolution);
  925.       xresolution *= asymmetry;
  926.       break;
  927.  
  928.     case 1: /* dots per inch */
  929.       break;
  930.  
  931.     case 2: /* dots per cm */
  932.       xresolution *= 2.54;
  933.       yresolution *= 2.54;
  934.       gimp_image_set_unit (image_ID, GIMP_UNIT_MM);
  935.       break;
  936.  
  937.     default:
  938.       g_message ("unknown density unit %d\nassuming dots per inch",
  939.              cinfo.density_unit);
  940.       break;
  941.     }
  942.  
  943.       gimp_image_set_resolution (image_ID, xresolution, yresolution);
  944.     }
  945. #endif /* GIMP_HAVE_RESOLUTION_INFO */
  946.  
  947.   /* Step 6: while (scan lines remain to be read) */
  948.   /*           jpeg_read_scanlines(...); */
  949.  
  950.   /* Here we use the library's state variable cinfo.output_scanline as the
  951.    * loop counter, so that we don't have to keep track ourselves.
  952.    */
  953.   while (cinfo.output_scanline < cinfo.output_height)
  954.     {
  955.       start = cinfo.output_scanline;
  956.       end   = cinfo.output_scanline + tile_height;
  957.       end   = MIN (end, cinfo.output_height);
  958.       scanlines = end - start;
  959.  
  960.       for (i = 0; i < scanlines; i++)
  961.     jpeg_read_scanlines (&cinfo, (JSAMPARRAY) &rowbuf[i], 1);
  962.  
  963.       if (preview) /* Add a dummy alpha channel -- convert buf to padded_buf */
  964.     {
  965.       guchar *dest = padded_buf;
  966.       guchar *src  = buf;
  967.       gint    num  = drawable->width * scanlines;
  968.  
  969.       switch (cinfo.output_components)
  970.         {
  971.         case 1:
  972.           for (i = 0; i < num; i++)
  973.         {
  974.           *(dest++) = *(src++);
  975.           *(dest++) = 255;
  976.         }
  977.           break;
  978.  
  979.         case 3:
  980.           for (i = 0; i < num; i++)
  981.         {
  982.           *(dest++) = *(src++);
  983.           *(dest++) = *(src++);
  984.           *(dest++) = *(src++);
  985.           *(dest++) = 255;
  986.         }
  987.           break;
  988.  
  989.         default:
  990.           g_warning ("JPEG - shouldn't have gotten here.\nReport to http://bugzilla.gnome.org/");
  991.           break;
  992.         }
  993.     }
  994.       else if (cinfo.out_color_space == JCS_CMYK) /* buf-> RGB in padded_buf */
  995.     {
  996.       guchar *dest = padded_buf;
  997.       guchar *src  = buf;
  998.       gint    num  = drawable->width * scanlines;
  999.  
  1000.       for (i = 0; i < num; i++)
  1001.         {
  1002.           guint r_c, g_m, b_y, a_k;
  1003.  
  1004.           r_c = *(src++);
  1005.           g_m = *(src++);
  1006.           b_y = *(src++);
  1007.           a_k = *(src++);
  1008.           *(dest++) = (r_c * a_k) / 255;
  1009.           *(dest++) = (g_m * a_k) / 255;
  1010.           *(dest++) = (b_y * a_k) / 255;
  1011.         }
  1012.     }
  1013.  
  1014.       gimp_pixel_rgn_set_rect (&pixel_rgn, padded_buf ? padded_buf : buf,
  1015.                    0, start, drawable->width, scanlines);
  1016.  
  1017.       if (runmode != GIMP_RUN_NONINTERACTIVE)
  1018.     {
  1019.       gimp_progress_update ((gdouble) cinfo.output_scanline / 
  1020.                 (gdouble) cinfo.output_height);
  1021.     }
  1022.     }
  1023.  
  1024.   /* Step 7: Finish decompression */
  1025.  
  1026.   jpeg_finish_decompress (&cinfo);
  1027.   /* We can ignore the return value since suspension is not possible
  1028.    * with the stdio data source.
  1029.    */
  1030.  
  1031.   /* Step 8: Release JPEG decompression object */
  1032.  
  1033.   /* This is an important step since it will release a good deal of memory. */
  1034.   jpeg_destroy_decompress (&cinfo);
  1035.  
  1036.   /* free up the temporary buffers */
  1037.   g_free (rowbuf);
  1038.   g_free (buf);
  1039.   g_free (padded_buf);
  1040.  
  1041.   /* After finish_decompress, we can close the input file.
  1042.    * Here we postpone it until after no more JPEG errors are possible,
  1043.    * so as to simplify the setjmp error logic above.  (Actually, I don't
  1044.    * think that jpeg_destroy can do an error exit, but why assume anything...)
  1045.    */
  1046.   fclose (infile);
  1047.  
  1048.   /* At this point you may want to check to see whether any corrupt-data
  1049.    * warnings occurred (test whether jerr.num_warnings is nonzero).
  1050.    */
  1051.  
  1052.   /* Tell the GIMP to display the image.
  1053.    */
  1054.   gimp_image_add_layer (image_ID, layer_ID, 0);
  1055.   gimp_drawable_flush (drawable);
  1056.  
  1057.   /* pw - Last of all, attach the parasites (couldn't do it earlier -
  1058.      there was no image. */
  1059.  
  1060. #ifdef GIMP_HAVE_PARASITES
  1061.   if (!preview)
  1062.     {
  1063.       if (comment_parasite)
  1064.     {
  1065.       gimp_image_parasite_attach (image_ID, comment_parasite);
  1066.       gimp_parasite_free (comment_parasite);
  1067.     }
  1068.     }
  1069. #endif /* GIMP_HAVE_PARASITES */
  1070.  
  1071.   return image_ID;
  1072. }
  1073.  
  1074. /*
  1075.  * sg - This is the best I can do, I'm afraid... I think it will fail
  1076.  * if something bad really happens (but it might not). If you have a
  1077.  * better solution, send it ;-)
  1078.  */ 
  1079. static void
  1080. background_error_exit (j_common_ptr cinfo)
  1081. {
  1082.   if (abort_me) 
  1083.     *abort_me = TRUE;
  1084.   (*cinfo->err->output_message) (cinfo);
  1085. }
  1086.  
  1087. static gboolean
  1088. background_jpeg_save (PreviewPersistent *pp)
  1089. {
  1090.   guchar *t;
  1091.   guchar *s;
  1092.   gint    i, j;
  1093.   gint    yend;
  1094.  
  1095.   if (pp->abort_me || (pp->cinfo.next_scanline >= pp->cinfo.image_height))
  1096.     {
  1097.       /* clean up... */
  1098.       if (pp->abort_me)
  1099.     {
  1100.       jpeg_abort_compress (&(pp->cinfo));
  1101.     }
  1102.       else
  1103.     {
  1104.       jpeg_finish_compress (&(pp->cinfo));
  1105.     }
  1106.  
  1107.       fclose (pp->outfile);
  1108.       jpeg_destroy_compress (&(pp->cinfo));
  1109.  
  1110.       g_free (pp->temp);
  1111.       g_free (pp->data);
  1112.  
  1113.       if (pp->drawable) 
  1114.     gimp_drawable_detach (pp->drawable);
  1115.  
  1116.       /* display the preview stuff */
  1117.       if (!pp->abort_me) 
  1118.     {
  1119.       struct stat buf;
  1120.       gchar       temp[128];
  1121.  
  1122.       stat (pp->file_name, &buf);
  1123.       g_snprintf (temp, sizeof (temp),
  1124.               _("Size: %lu bytes (%02.01f kB)"),
  1125.               buf.st_size, (float) (buf.st_size) / 1024.0);
  1126.       gtk_label_set_text (GTK_LABEL (preview_size), temp);
  1127.     
  1128.       /* and load the preview */
  1129.       load_image (pp->file_name, GIMP_RUN_NONINTERACTIVE, TRUE);
  1130.     }
  1131.  
  1132.       /* we cleanup here (load_image doesn't run in the background) */
  1133.       unlink (pp->file_name);
  1134.       g_free (pp->file_name);
  1135.  
  1136.       if (abort_me == &(pp->abort_me)) 
  1137.     abort_me = NULL;
  1138.  
  1139.       g_free (pp);
  1140.  
  1141.       gimp_displays_flush ();
  1142.       gdk_flush ();
  1143.  
  1144.       return FALSE;
  1145.     }
  1146.   else
  1147.     {
  1148.       if ((pp->cinfo.next_scanline % pp->tile_height) == 0)
  1149.     {
  1150.       yend = pp->cinfo.next_scanline + pp->tile_height;
  1151.       yend = MIN (yend, pp->cinfo.image_height);
  1152.       gimp_pixel_rgn_get_rect (&pp->pixel_rgn, pp->data, 0, 
  1153.                    pp->cinfo.next_scanline,
  1154.                    pp->cinfo.image_width,
  1155.                    (yend - pp->cinfo.next_scanline));
  1156.       pp->src = pp->data;
  1157.     }
  1158.  
  1159.       t = pp->temp;
  1160.       s = pp->src;
  1161.       i = pp->cinfo.image_width;
  1162.  
  1163.       while (i--)
  1164.     {
  1165.       for (j = 0; j < pp->cinfo.input_components; j++)
  1166.         *t++ = *s++;
  1167.       if (pp->has_alpha)  /* ignore alpha channel */
  1168.         s++;
  1169.     }
  1170.  
  1171.       pp->src += pp->rowstride;
  1172.       jpeg_write_scanlines (&(pp->cinfo), (JSAMPARRAY) &(pp->temp), 1);
  1173.  
  1174.       return TRUE;
  1175.     }
  1176. }
  1177.  
  1178. static gboolean
  1179. save_image (gchar    *filename,
  1180.         gint32    image_ID,
  1181.         gint32    drawable_ID,
  1182.         gint32    orig_image_ID,
  1183.         gboolean  preview)
  1184. {
  1185.   GimpPixelRgn   pixel_rgn;
  1186.   GimpDrawable  *drawable;
  1187.   GimpImageType  drawable_type;
  1188.   struct jpeg_compress_struct cinfo;
  1189.   struct my_error_mgr         jerr;
  1190.   FILE     * volatile outfile;
  1191.   guchar   *temp, *t;
  1192.   guchar   *data;
  1193.   guchar   *src, *s;
  1194.   gchar    *name;
  1195.   gboolean  has_alpha;
  1196.   gint      rowstride, yend;
  1197.   gint      i, j;
  1198.  
  1199.   drawable = gimp_drawable_get (drawable_ID);
  1200.   drawable_type = gimp_drawable_type (drawable_ID);
  1201.   gimp_pixel_rgn_init (&pixel_rgn, drawable,
  1202.                0, 0, drawable->width, drawable->height, FALSE, FALSE);
  1203.  
  1204.   if (!preview) 
  1205.     {
  1206.       name = g_strdup_printf (_("Saving %s:"), filename);
  1207.       gimp_progress_init (name);
  1208.       g_free (name);
  1209.     }
  1210.  
  1211.   /* Step 1: allocate and initialize JPEG compression object */
  1212.  
  1213.   /* We have to set up the error handler first, in case the initialization
  1214.    * step fails.  (Unlikely, but it could happen if you are out of memory.)
  1215.    * This routine fills in the contents of struct jerr, and returns jerr's
  1216.    * address which we place into the link field in cinfo.
  1217.    */
  1218.   cinfo.err = jpeg_std_error (&jerr.pub);
  1219.   jerr.pub.error_exit = my_error_exit;
  1220.  
  1221.   outfile = NULL;
  1222.   /* Establish the setjmp return context for my_error_exit to use. */
  1223.   if (setjmp (jerr.setjmp_buffer))
  1224.     {
  1225.       /* If we get here, the JPEG code has signaled an error.
  1226.        * We need to clean up the JPEG object, close the input file, and return.
  1227.        */
  1228.       jpeg_destroy_compress (&cinfo);
  1229.       if (outfile)
  1230.     fclose (outfile);
  1231.       if (drawable)
  1232.     gimp_drawable_detach (drawable);
  1233.  
  1234.       return FALSE;
  1235.     }
  1236.  
  1237.   /* Now we can initialize the JPEG compression object. */
  1238.   jpeg_create_compress (&cinfo);
  1239.  
  1240.   /* Step 2: specify data destination (eg, a file) */
  1241.   /* Note: steps 2 and 3 can be done in either order. */
  1242.  
  1243.   /* Here we use the library-supplied code to send compressed data to a
  1244.    * stdio stream.  You can also write your own code to do something else.
  1245.    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
  1246.    * requires it in order to write binary files.
  1247.    */
  1248.   if ((outfile = fopen (filename, "wb")) == NULL)
  1249.     {
  1250.       g_message ("can't open %s\n", filename);
  1251.       return FALSE;
  1252.     }
  1253.   jpeg_stdio_dest (&cinfo, outfile);
  1254.  
  1255.   /* Get the input image and a pointer to its data.
  1256.    */
  1257.   switch (drawable_type)
  1258.     {
  1259.     case GIMP_RGB_IMAGE:
  1260.     case GIMP_GRAY_IMAGE:
  1261.       /* # of color components per pixel */
  1262.       cinfo.input_components = drawable->bpp;
  1263.       has_alpha = FALSE;
  1264.       break;
  1265.  
  1266.     case GIMP_RGBA_IMAGE:
  1267.     case GIMP_GRAYA_IMAGE:
  1268.       /*gimp_message ("jpeg: image contains a-channel info which will be lost");*/
  1269.       /* # of color components per pixel (minus the GIMP alpha channel) */
  1270.       cinfo.input_components = drawable->bpp - 1;
  1271.       has_alpha = TRUE;
  1272.       break;
  1273.  
  1274.     case GIMP_INDEXED_IMAGE:
  1275.       /*gimp_message ("jpeg: cannot operate on indexed color images");*/
  1276.       return FALSE;
  1277.       break;
  1278.  
  1279.     default:
  1280.       /*gimp_message ("jpeg: cannot operate on unknown image types");*/
  1281.       return FALSE;
  1282.       break;
  1283.     }
  1284.  
  1285.   /* Step 3: set parameters for compression */
  1286.  
  1287.   /* First we supply a description of the input image.
  1288.    * Four fields of the cinfo struct must be filled in:
  1289.    */
  1290.   /* image width and height, in pixels */
  1291.   cinfo.image_width  = drawable->width;
  1292.   cinfo.image_height = drawable->height;
  1293.   /* colorspace of input image */
  1294.   cinfo.in_color_space = (drawable_type == GIMP_RGB_IMAGE ||
  1295.               drawable_type == GIMP_RGBA_IMAGE)
  1296.     ? JCS_RGB : JCS_GRAYSCALE;
  1297.   /* Now use the library's routine to set default compression parameters.
  1298.    * (You must set at least cinfo.in_color_space before calling this,
  1299.    * since the defaults depend on the source color space.)
  1300.    */
  1301.   jpeg_set_defaults (&cinfo);
  1302.  
  1303.   jpeg_set_quality (&cinfo, (gint) (jsvals.quality * 100), jsvals.baseline);
  1304.   cinfo.smoothing_factor = (gint) (jsvals.smoothing * 100);
  1305.   cinfo.optimize_coding = jsvals.optimize;
  1306.  
  1307. #ifdef HAVE_PROGRESSIVE_JPEG
  1308.   if (jsvals.progressive) 
  1309.     {
  1310.       jpeg_simple_progression (&cinfo);
  1311.     }
  1312. #endif /* HAVE_PROGRESSIVE_JPEG */
  1313.  
  1314.   switch (jsvals.subsmp) 
  1315.     {
  1316.     case 0:
  1317.     default:
  1318.       cinfo.comp_info[0].h_samp_factor = 2;
  1319.       cinfo.comp_info[0].v_samp_factor = 2;
  1320.       cinfo.comp_info[1].h_samp_factor = 1;
  1321.       cinfo.comp_info[1].v_samp_factor = 1;
  1322.       cinfo.comp_info[2].h_samp_factor = 1;
  1323.       cinfo.comp_info[2].v_samp_factor = 1;
  1324.       break;
  1325.  
  1326.     case 1:
  1327.       cinfo.comp_info[0].h_samp_factor = 2;
  1328.       cinfo.comp_info[0].v_samp_factor = 1;
  1329.       cinfo.comp_info[1].h_samp_factor = 1;
  1330.       cinfo.comp_info[1].v_samp_factor = 1;
  1331.       cinfo.comp_info[2].h_samp_factor = 1;
  1332.       cinfo.comp_info[2].v_samp_factor = 1;
  1333.       break;
  1334.  
  1335.     case 2:
  1336.       cinfo.comp_info[0].h_samp_factor = 1;
  1337.       cinfo.comp_info[0].v_samp_factor = 1;
  1338.       cinfo.comp_info[1].h_samp_factor = 1;
  1339.       cinfo.comp_info[1].v_samp_factor = 1;
  1340.       cinfo.comp_info[2].h_samp_factor = 1;
  1341.       cinfo.comp_info[2].v_samp_factor = 1;
  1342.       break;
  1343.     }
  1344.   
  1345.   cinfo.restart_interval = 0;
  1346.   cinfo.restart_in_rows = jsvals.restart;
  1347.  
  1348.   switch (jsvals.dct) 
  1349.     {
  1350.     case 0:
  1351.     default:
  1352.       cinfo.dct_method = JDCT_ISLOW;
  1353.       break;
  1354.  
  1355.     case 1:
  1356.       cinfo.dct_method = JDCT_IFAST;
  1357.       break;
  1358.  
  1359.     case 2:
  1360.       cinfo.dct_method = JDCT_FLOAT;
  1361.       break;
  1362.     }
  1363.  
  1364. #ifdef GIMP_HAVE_RESOLUTION_INFO
  1365.   {
  1366.     gdouble xresolution;
  1367.     gdouble yresolution;
  1368.  
  1369.     gimp_image_get_resolution (orig_image_ID, &xresolution, &yresolution);
  1370.  
  1371.     if (xresolution > 1e-5 && yresolution > 1e-5)
  1372.       {
  1373.     gdouble factor;
  1374.  
  1375.     factor = gimp_unit_get_factor (gimp_image_get_unit (orig_image_ID));
  1376.  
  1377.     if (factor == 2.54 /* cm */ ||
  1378.         factor == 25.4 /* mm */)
  1379.       {
  1380.         cinfo.density_unit = 2;  /* dots per cm */
  1381.  
  1382.         xresolution /= 2.54;
  1383.         yresolution /= 2.54;
  1384.       }
  1385.     else
  1386.       {
  1387.         cinfo.density_unit = 1;  /* dots per inch */
  1388.       }
  1389.  
  1390.     cinfo.X_density = xresolution;
  1391.     cinfo.Y_density = yresolution;
  1392.       }
  1393.   }
  1394. #endif /* GIMP_HAVE_RESOLUTION_INFO */
  1395.  
  1396.   /* Step 4: Start compressor */
  1397.  
  1398.   /* TRUE ensures that we will write a complete interchange-JPEG file.
  1399.    * Pass TRUE unless you are very sure of what you're doing.
  1400.    */
  1401.   jpeg_start_compress (&cinfo, TRUE);
  1402.  
  1403.   /* Step 4.1: Write the comment out - pw */
  1404.   if (image_comment && *image_comment)
  1405.     {
  1406.       jpeg_write_marker (&cinfo,
  1407.              JPEG_COM,
  1408.              image_comment,
  1409.              strlen (image_comment));
  1410.     }
  1411.     
  1412.   /* Step 5: while (scan lines remain to be written) */
  1413.   /*           jpeg_write_scanlines(...); */
  1414.  
  1415.   /* Here we use the library's state variable cinfo.next_scanline as the
  1416.    * loop counter, so that we don't have to keep track ourselves.
  1417.    * To keep things simple, we pass one scanline per call; you can pass
  1418.    * more if you wish, though.
  1419.    */
  1420.   /* JSAMPLEs per row in image_buffer */
  1421.   rowstride = drawable->bpp * drawable->width;
  1422.   temp = g_new (guchar, cinfo.image_width * cinfo.input_components);
  1423.   data = g_new (guchar, rowstride * gimp_tile_height ());
  1424.  
  1425.   /* fault if cinfo.next_scanline isn't initially a multiple of
  1426.    * gimp_tile_height */
  1427.   src = NULL;
  1428.  
  1429.   /*
  1430.    * sg - if we preview, we want this to happen in the background -- do
  1431.    * not duplicate code in the future; for now, it's OK
  1432.    */
  1433.  
  1434.   if (preview) 
  1435.     {
  1436.       PreviewPersistent *pp = g_new (PreviewPersistent, 1);
  1437.       
  1438.       /* pass all the information we need */
  1439.       pp->cinfo       = cinfo;
  1440.       pp->tile_height = gimp_tile_height();
  1441.       pp->data        = data;
  1442.       pp->outfile     = outfile;
  1443.       pp->has_alpha   = has_alpha;
  1444.       pp->rowstride   = rowstride;
  1445.       pp->temp        = temp;
  1446.       pp->data        = data;
  1447.       pp->drawable    = drawable;
  1448.       pp->pixel_rgn   = pixel_rgn;
  1449.       pp->src         = NULL;
  1450.       pp->file_name   = filename;
  1451.       
  1452.       pp->abort_me    = FALSE;
  1453.       abort_me = &(pp->abort_me);
  1454.       
  1455.       jerr.pub.error_exit = background_error_exit;
  1456.  
  1457.       gtk_idle_add ((GtkFunction) background_jpeg_save, (gpointer) pp);
  1458.       
  1459.       /* background_jpeg_save() will cleanup as needed */
  1460.       return TRUE;
  1461.     } 
  1462.  
  1463.   while (cinfo.next_scanline < cinfo.image_height)
  1464.     {
  1465.       if ((cinfo.next_scanline % gimp_tile_height ()) == 0)
  1466.     {
  1467.       yend = cinfo.next_scanline + gimp_tile_height ();
  1468.       yend = MIN (yend, cinfo.image_height);
  1469.       gimp_pixel_rgn_get_rect (&pixel_rgn, data, 
  1470.                    0, cinfo.next_scanline, 
  1471.                    cinfo.image_width,
  1472.                    (yend - cinfo.next_scanline));
  1473.       src = data;
  1474.     }
  1475.  
  1476.       t = temp;
  1477.       s = src;
  1478.       i = cinfo.image_width;
  1479.  
  1480.       while (i--)
  1481.     {
  1482.       for (j = 0; j < cinfo.input_components; j++)
  1483.         *t++ = *s++;
  1484.       if (has_alpha)  /* ignore alpha channel */
  1485.         s++;
  1486.     }
  1487.  
  1488.       src += rowstride;
  1489.       jpeg_write_scanlines (&cinfo, (JSAMPARRAY) &temp, 1);
  1490.  
  1491.       if ((cinfo.next_scanline % 5) == 0)
  1492.     gimp_progress_update ((gdouble) cinfo.next_scanline / 
  1493.                   (gdouble) cinfo.image_height);
  1494.     }
  1495.  
  1496.   /* Step 6: Finish compression */
  1497.   jpeg_finish_compress (&cinfo);
  1498.   /* After finish_compress, we can close the output file. */
  1499.   fclose (outfile);
  1500.  
  1501.   /* Step 7: release JPEG compression object */
  1502.  
  1503.   /* This is an important step since it will release a good deal of memory. */
  1504.   jpeg_destroy_compress (&cinfo);
  1505.   /* free the temporary buffer */
  1506.   g_free (temp);
  1507.   g_free (data);
  1508.  
  1509.   /* And we're done! */
  1510.   /*gimp_do_progress (1, 1);*/
  1511.  
  1512.   gimp_drawable_detach (drawable);
  1513.  
  1514.   return TRUE;
  1515. }
  1516.  
  1517. static void
  1518. make_preview (void)
  1519. {
  1520.   gchar *tn;
  1521.  
  1522.   destroy_preview ();
  1523.  
  1524.   if (jsvals.preview) 
  1525.     {
  1526.       tn = gimp_temp_name ("jpeg");
  1527.       save_image (tn, 
  1528.           image_ID_global,
  1529.           drawable_ID_global, 
  1530.           orig_image_ID_global, 
  1531.           TRUE);
  1532.     }
  1533.   else 
  1534.     {
  1535.       gtk_label_set_text (GTK_LABEL (preview_size), _("Size: unknown"));
  1536.       gtk_widget_draw (preview_size, NULL);
  1537.       
  1538.       gimp_displays_flush ();
  1539.       gdk_flush();
  1540.     }
  1541. }
  1542.  
  1543. static void
  1544. destroy_preview (void)
  1545. {
  1546.   if (abort_me) 
  1547.     {
  1548.       *abort_me = TRUE;   /* signal the background save to stop */
  1549.     }
  1550.  
  1551.   if (drawable_global) 
  1552.     {
  1553.       gimp_drawable_detach (drawable_global);
  1554.       drawable_global = NULL;
  1555.     }
  1556.  
  1557.   if (layer_ID_global != -1 && image_ID_global != -1) 
  1558.     {
  1559.       /*  assuming that reference counting is working correctly, 
  1560.       we do not need to delete the layer, removing it from
  1561.       the image should be sufficient  */
  1562.       gimp_image_remove_layer (image_ID_global, layer_ID_global);
  1563.       
  1564.       layer_ID_global = -1;
  1565.     }
  1566. }
  1567.  
  1568. static gboolean
  1569. save_dialog (void)
  1570. {
  1571.   GtkWidget *dlg;
  1572.   GtkWidget *vbox;
  1573.   GtkWidget *main_vbox;
  1574.   GtkWidget *label;
  1575.   GtkWidget *scale;
  1576.   GtkWidget *frame;
  1577.   GtkWidget *table;
  1578.   GtkWidget *toggle;
  1579.   GtkWidget *abox;
  1580.   GtkObject *scale_data;
  1581.  
  1582.   GtkWidget *progressive;
  1583.   /*   GtkWidget *baseline;  */
  1584.   GtkWidget *restart;
  1585.  
  1586.   GtkWidget *preview;
  1587.   /* GtkWidget *preview_size; -- global */
  1588.  
  1589.   GtkWidget *menu;
  1590.   
  1591.   GtkWidget *text;
  1592.   GtkWidget *com_frame;
  1593.   GtkWidget *com_table;
  1594.   GtkWidget *vscrollbar;
  1595.   
  1596.   GtkWidget *prv_frame;
  1597.   GimpImageType dtype;
  1598.  
  1599.   dlg = gimp_dialog_new (_("Save as JPEG"), "jpeg",
  1600.              gimp_standard_help_func, "filters/jpeg.html",
  1601.              GTK_WIN_POS_MOUSE,
  1602.              FALSE, TRUE, FALSE,
  1603.  
  1604.              _("OK"), save_ok_callback,
  1605.              NULL, NULL, NULL, TRUE, FALSE,
  1606.              _("Cancel"), gtk_widget_destroy,
  1607.              NULL, 1, NULL, FALSE, TRUE,
  1608.  
  1609.              NULL);
  1610.  
  1611.   gtk_signal_connect (GTK_OBJECT (dlg), "destroy",
  1612.               GTK_SIGNAL_FUNC (save_close_callback),
  1613.               NULL);
  1614.  
  1615.   main_vbox = gtk_vbox_new (FALSE, 4);
  1616.   gtk_container_set_border_width (GTK_CONTAINER (main_vbox), 6);
  1617.   gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dlg)->vbox), main_vbox,
  1618.               TRUE, TRUE, 0);
  1619.   gtk_widget_show (main_vbox);
  1620.  
  1621.   /* sg - preview */
  1622.   prv_frame = gtk_frame_new (_("Image Preview"));
  1623.   gtk_frame_set_shadow_type (GTK_FRAME (prv_frame), GTK_SHADOW_ETCHED_IN);
  1624.   gtk_box_pack_start (GTK_BOX (main_vbox), prv_frame, FALSE, FALSE, 0);
  1625.  
  1626.   vbox = gtk_vbox_new (FALSE, 2);
  1627.   gtk_container_set_border_width (GTK_CONTAINER (vbox), 4);
  1628.   gtk_container_add (GTK_CONTAINER (prv_frame), vbox);
  1629.   gtk_widget_show (vbox);
  1630.  
  1631.   preview = gtk_check_button_new_with_label (_("Preview (in image window)"));
  1632.   gtk_box_pack_start (GTK_BOX (vbox), preview, FALSE, FALSE, 0);
  1633.   gtk_signal_connect (GTK_OBJECT (preview), "toggled",
  1634.               GTK_SIGNAL_FUNC (gimp_toggle_button_update),
  1635.               &jsvals.preview);
  1636.   gtk_signal_connect (GTK_OBJECT (preview), "toggled",
  1637.               GTK_SIGNAL_FUNC (make_preview),
  1638.               NULL);
  1639.   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (preview), jsvals.preview);
  1640.   gtk_widget_show (preview);
  1641.  
  1642.   preview_size = gtk_label_new (_("Size: unknown"));
  1643.   gtk_misc_set_alignment (GTK_MISC (preview_size), 0.0, 0.5);
  1644.   gtk_box_pack_start (GTK_BOX (vbox), preview_size, FALSE, FALSE, 0);
  1645.   gtk_widget_show (preview_size);
  1646.  
  1647.   gtk_widget_show (prv_frame);
  1648.  
  1649.   make_preview ();
  1650.  
  1651.   /*  parameter settings  */
  1652.   frame = gtk_frame_new (_("Parameter Settings"));
  1653.   gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_ETCHED_IN);
  1654.   gtk_box_pack_start (GTK_BOX (main_vbox), frame, FALSE, FALSE, 0);
  1655.  
  1656.   table = gtk_table_new (8, 3, FALSE);
  1657.   gtk_table_set_col_spacings (GTK_TABLE (table), 4);
  1658.   gtk_table_set_row_spacings (GTK_TABLE (table), 4);
  1659.   gtk_container_set_border_width (GTK_CONTAINER (table), 4);
  1660.   gtk_container_add (GTK_CONTAINER (frame), table);
  1661.  
  1662.   label = gtk_label_new (_("Quality:"));
  1663.   gtk_misc_set_alignment (GTK_MISC (label), 1.0, 1.0);
  1664.   gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1,
  1665.             GTK_FILL | GTK_SHRINK, GTK_FILL, 0, 0);
  1666.   gtk_widget_show (label);
  1667.  
  1668.   scale_data = gtk_adjustment_new (jsvals.quality, 0.0, 1.0, 0.01, 0.01, 0.0);
  1669.   scale = gtk_hscale_new (GTK_ADJUSTMENT (scale_data));
  1670.   gtk_widget_set_usize (scale, SCALE_WIDTH, 0);
  1671.   gtk_table_attach (GTK_TABLE (table), scale, 1, 3, 0, 1,
  1672.             GTK_FILL | GTK_EXPAND, GTK_FILL, 0, 0);
  1673.   gtk_scale_set_value_pos (GTK_SCALE (scale), GTK_POS_TOP);
  1674.   gtk_scale_set_digits (GTK_SCALE (scale), 2);
  1675.   gtk_range_set_update_policy (GTK_RANGE (scale), GTK_UPDATE_DELAYED);
  1676.   gtk_signal_connect (GTK_OBJECT (scale_data), "value_changed",
  1677.               GTK_SIGNAL_FUNC (gimp_double_adjustment_update),
  1678.               &jsvals.quality);
  1679.   gtk_signal_connect (GTK_OBJECT (scale_data), "value_changed",
  1680.               GTK_SIGNAL_FUNC (make_preview),
  1681.               NULL);
  1682.   gtk_widget_show (scale);
  1683.  
  1684.   label = gtk_label_new (_("Smoothing:"));
  1685.   gtk_misc_set_alignment (GTK_MISC (label), 1.0, 1.0);
  1686.   gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2,
  1687.             GTK_FILL | GTK_SHRINK, GTK_FILL, 0, 0);
  1688.   gtk_widget_show (label);
  1689.  
  1690.   scale_data = gtk_adjustment_new (jsvals.smoothing, 0.0, 1.0, 0.01, 0.01, 0.0);
  1691.   scale = gtk_hscale_new (GTK_ADJUSTMENT (scale_data));
  1692.   gtk_widget_set_usize (scale, SCALE_WIDTH, 0);
  1693.   gtk_table_attach (GTK_TABLE (table), scale, 1, 3, 1, 2,
  1694.             GTK_FILL | GTK_EXPAND, GTK_FILL, 0, 0);
  1695.   gtk_scale_set_value_pos (GTK_SCALE (scale), GTK_POS_TOP);
  1696.   gtk_scale_set_digits (GTK_SCALE (scale), 2);
  1697.   gtk_range_set_update_policy (GTK_RANGE (scale), GTK_UPDATE_DELAYED);
  1698.   gtk_signal_connect (GTK_OBJECT (scale_data), "value_changed",
  1699.               GTK_SIGNAL_FUNC (gimp_double_adjustment_update),
  1700.               &jsvals.smoothing);
  1701.   gtk_signal_connect (GTK_OBJECT (scale_data), "value_changed",
  1702.               GTK_SIGNAL_FUNC (make_preview),
  1703.               NULL);
  1704.   gtk_widget_show (scale);
  1705.  
  1706.   /* sg - have to init scale here */
  1707.   scale_data = gtk_adjustment_new ((jsvals.restart == 0) ? 1 : jsvals.restart,
  1708.                    1, 64, 1, 1, 0.0);
  1709.   restart_markers_scale = gtk_hscale_new (GTK_ADJUSTMENT (scale_data));
  1710.  
  1711.   restart = gtk_check_button_new_with_label (_("Restart markers"));
  1712.   gtk_table_attach (GTK_TABLE (table), restart, 0, 1, 2, 3,
  1713.             GTK_FILL, 0, 0, 0);
  1714.   gtk_signal_connect (GTK_OBJECT (restart), "toggled",
  1715.               GTK_SIGNAL_FUNC (save_restart_toggle_update),
  1716.               scale_data);
  1717.   gtk_widget_show (restart);
  1718.  
  1719.   restart_markers_label = gtk_label_new (_("Restart frequency (rows):"));
  1720.   gtk_misc_set_alignment (GTK_MISC (restart_markers_label), 1.0, 1.0);
  1721.   gtk_table_attach (GTK_TABLE (table), restart_markers_label, 0, 1, 3, 4,
  1722.             GTK_FILL | GTK_SHRINK, GTK_FILL, 0, 0);
  1723.   gtk_widget_show (restart_markers_label);
  1724.  
  1725.   abox = gtk_alignment_new (0.5, 1.0, 1.0, 0.0);
  1726.   gtk_table_attach (GTK_TABLE (table), abox, 1, 3, 2, 4,
  1727.             GTK_EXPAND | GTK_FILL, GTK_SHRINK | GTK_FILL, 0, 0);
  1728.   gtk_widget_show (abox);
  1729.  
  1730.   gtk_widget_set_usize (restart_markers_scale, SCALE_WIDTH, 0);
  1731.   gtk_container_add (GTK_CONTAINER (abox), restart_markers_scale);
  1732.   gtk_scale_set_value_pos (GTK_SCALE (restart_markers_scale), GTK_POS_TOP);
  1733.   gtk_scale_set_digits (GTK_SCALE (restart_markers_scale), 0);
  1734.   gtk_range_set_update_policy (GTK_RANGE (restart_markers_scale),
  1735.                    GTK_UPDATE_DELAYED);
  1736.  
  1737.   gtk_signal_connect (GTK_OBJECT (scale_data), "value_changed",
  1738.                       GTK_SIGNAL_FUNC (save_restart_update),
  1739.                       restart);
  1740.  
  1741.   gtk_widget_set_sensitive (restart_markers_label, 
  1742.                 (jsvals.restart ? TRUE : FALSE));
  1743.   gtk_widget_set_sensitive (restart_markers_scale,
  1744.                 (jsvals.restart ? TRUE : FALSE));
  1745.  
  1746.   gtk_widget_show (restart_markers_scale);
  1747.  
  1748.   toggle = gtk_check_button_new_with_label (_("Optimize"));
  1749.   gtk_table_attach (GTK_TABLE (table), toggle, 0, 3, 4, 5,
  1750.             GTK_FILL, 0, 0, 0);
  1751.   gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
  1752.               GTK_SIGNAL_FUNC (gimp_toggle_button_update),
  1753.               &jsvals.optimize);
  1754.   gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
  1755.               GTK_SIGNAL_FUNC (make_preview),
  1756.               NULL);
  1757.   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), jsvals.optimize);
  1758.   gtk_widget_show (toggle);
  1759.  
  1760.   progressive = gtk_check_button_new_with_label (_("Progressive"));
  1761.   gtk_table_attach (GTK_TABLE (table), progressive, 0, 3, 5, 6,
  1762.             GTK_FILL, 0, 0, 0);
  1763.   gtk_signal_connect (GTK_OBJECT (progressive), "toggled",
  1764.               GTK_SIGNAL_FUNC (gimp_toggle_button_update),
  1765.               &jsvals.progressive);
  1766.   gtk_signal_connect (GTK_OBJECT (progressive), "toggled",
  1767.               GTK_SIGNAL_FUNC (make_preview),
  1768.               NULL);
  1769.   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (progressive),
  1770.                 jsvals.progressive);
  1771.   gtk_widget_show (progressive);
  1772.  
  1773. #ifndef HAVE_PROGRESSIVE_JPEG
  1774.   gtk_widget_set_sensitive (progressive, FALSE);
  1775. #endif
  1776.   
  1777.   /* 
  1778.    * Commented out since it triggers a bug in libjpeg if
  1779.    * used with low quality setting (bug #57727).
  1780.    *
  1781.    * baseline = gtk_check_button_new_with_label (_("Force baseline JPEG (Readable by all decoders)"));
  1782.    * gtk_table_attach (GTK_TABLE (table), baseline, 0, 3, 6, 7,
  1783.    *             GTK_FILL, 0, 0, 0);
  1784.    * gtk_signal_connect (GTK_OBJECT (baseline), "toggled",
  1785.    *               GTK_SIGNAL_FUNC (gimp_toggle_button_update),
  1786.    *               &jsvals.baseline);
  1787.    * gtk_signal_connect (GTK_OBJECT (baseline), "toggled",
  1788.    *              GTK_SIGNAL_FUNC (make_preview),
  1789.    *              NULL);
  1790.    * gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (baseline),
  1791.    *                jsvals.baseline);
  1792.    * gtk_widget_show (baseline);
  1793.    */
  1794.  
  1795.   /* Subsampling */
  1796.   menu = 
  1797.     gimp_option_menu_new2 (FALSE, 
  1798.                menu_callback, 
  1799.                &jsvals.subsmp, GINT_TO_POINTER (jsvals.subsmp),
  1800.                "2x2,1x1,1x1",  GINT_TO_POINTER (0), NULL, 
  1801.                "2x1,1x1,1x1 (4:2:2)", GINT_TO_POINTER (1), NULL,
  1802.                "1x1,1x1,1x1",  GINT_TO_POINTER (2), NULL,
  1803.                NULL);
  1804.  
  1805.   gimp_table_attach_aligned (GTK_TABLE (table), 1, 6, 
  1806.                  _("Subsampling:"),
  1807.                  1.0, 0.5,
  1808.                  menu, 1, FALSE);
  1809.  
  1810.   /* DCT method */
  1811.   menu = 
  1812.     gimp_option_menu_new2 (FALSE, 
  1813.                menu_callback, 
  1814.                &jsvals.dct, GINT_TO_POINTER (jsvals.dct),
  1815.                _("Fast Integer"),   GINT_TO_POINTER (1), NULL, 
  1816.                _("Integer"),        GINT_TO_POINTER (0), NULL,
  1817.                _("Floating-Point"), GINT_TO_POINTER (2), NULL,
  1818.                NULL);
  1819.  
  1820.   gimp_table_attach_aligned (GTK_TABLE (table), 1, 7, 
  1821.                  _("DCT method (Speed/quality tradeoff):"),
  1822.                  1.0, 0.5,
  1823.                  menu, 1, FALSE);
  1824.  
  1825.   dtype = gimp_drawable_type (drawable_ID_global);
  1826.   if (dtype != GIMP_RGB_IMAGE && dtype != GIMP_RGBA_IMAGE) 
  1827.     gtk_widget_set_sensitive (menu, FALSE);
  1828.  
  1829.   com_frame = gtk_frame_new (_("Image comments"));
  1830.   gtk_frame_set_shadow_type (GTK_FRAME (com_frame), GTK_SHADOW_ETCHED_IN);
  1831.   gtk_box_pack_start (GTK_BOX (main_vbox), com_frame, TRUE, TRUE, 0);
  1832.  
  1833.   com_table = gtk_table_new (1, 2, FALSE);
  1834.   gtk_container_set_border_width (GTK_CONTAINER (com_table), 4);
  1835.   gtk_container_add (GTK_CONTAINER (com_frame), com_table);
  1836.  
  1837.   text = gtk_text_new (NULL, NULL);
  1838.   gtk_text_set_editable (GTK_TEXT (text), TRUE);
  1839.   gtk_widget_set_usize (text, -1, 3); /* HB: restrict to 3 line height 
  1840.                        * to allow 800x600 mode */
  1841.   if (image_comment) 
  1842.     gtk_text_insert (GTK_TEXT (text), NULL, NULL, NULL, image_comment, -1);
  1843.   gtk_table_attach (GTK_TABLE (com_table), text, 0, 1, 0, 1,
  1844.                     GTK_EXPAND | GTK_SHRINK | GTK_FILL,
  1845.                     GTK_EXPAND | GTK_SHRINK | GTK_FILL, 0, 0);
  1846.   
  1847.   /* Add a vertical scrollbar to the GtkText widget */
  1848.   vscrollbar = gtk_vscrollbar_new (GTK_TEXT (text)->vadj);
  1849.   gtk_table_attach (GTK_TABLE (com_table), vscrollbar, 1, 2, 0, 1,
  1850.                     GTK_FILL, GTK_EXPAND | GTK_SHRINK | GTK_FILL, 0, 0);
  1851.   gtk_widget_show (vscrollbar);
  1852.  
  1853.   /* pw - mild hack here.  I didn't like redoing the comment string
  1854.    * each time a character was typed, so I associated the text area
  1855.    * with the dialog.  That way, just before the dialog destroys
  1856.    * itself (once the ok button is hit) it can save whatever was in
  1857.    * the comment text area to the comment string.  See the
  1858.    * save-ok-callback for more details.  */
  1859.   
  1860.   gtk_object_set_data (GTK_OBJECT (dlg), "text", text); 
  1861.   
  1862.   gtk_widget_show (text);
  1863.   gtk_widget_show (com_frame);
  1864.   gtk_widget_show (com_table);
  1865.  
  1866.   gtk_widget_show (frame);
  1867.   gtk_widget_show (table);
  1868.   gtk_widget_show (dlg);
  1869.  
  1870.   gtk_main ();
  1871.   gdk_flush ();
  1872.  
  1873.   return jsint.run;
  1874. }
  1875.  
  1876. /*  Save interface functions  */
  1877.  
  1878. static void
  1879. save_close_callback (GtkWidget *widget,
  1880.              gpointer   data)
  1881. {
  1882.   destroy_preview ();
  1883.   gimp_displays_flush ();
  1884.   gtk_main_quit ();
  1885. }
  1886.  
  1887. static void
  1888. save_ok_callback (GtkWidget *widget,
  1889.           gpointer   data)
  1890. {
  1891.   GtkWidget *text;
  1892.  
  1893.   jsint.run = TRUE;
  1894.  
  1895.   /* pw - get the comment text object and grab it's data */
  1896.   text = gtk_object_get_data (GTK_OBJECT (data), "text");
  1897.   
  1898.   /* pw - gtk_editable_get_chars allocates a copy of the string, so
  1899.    * don't worry about the gtk_widget_destroy killing it.  */
  1900.  
  1901.   g_free (image_comment);
  1902.   image_comment = NULL;
  1903.  
  1904.   if (text)
  1905.     image_comment = gtk_editable_get_chars (GTK_EDITABLE (text), 0, -1);
  1906.  
  1907.   gtk_widget_destroy (GTK_WIDGET (data));
  1908. }
  1909.  
  1910. static void
  1911. save_restart_toggle_update (GtkWidget     *widget,
  1912.                 GtkAdjustment *adjustment)
  1913. {
  1914.   save_restart_update (adjustment, widget);
  1915. }
  1916.  
  1917. static void
  1918. save_restart_update (GtkAdjustment *adjustment,
  1919.              GtkWidget     *toggle)
  1920. {
  1921.   jsvals.restart = GTK_TOGGLE_BUTTON (toggle)->active ? adjustment->value : 0;
  1922.  
  1923.   gtk_widget_set_sensitive (restart_markers_label,
  1924.                 (jsvals.restart ? TRUE : FALSE));
  1925.   gtk_widget_set_sensitive (restart_markers_scale,
  1926.                 (jsvals.restart ? TRUE : FALSE));
  1927.           
  1928.   make_preview ();
  1929. }
  1930.  
  1931. static void
  1932. menu_callback (GtkWidget *widget,
  1933.            gpointer   data)
  1934. {
  1935.   gimp_menu_item_update (widget, data);
  1936.   make_preview ();
  1937. }
  1938.